package com.bbm.communitysystem.controller.waste;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.core.oss.OSS;
import com.bbm.communitysystem.domain.*;
import com.bbm.communitysystem.domain.dto.WasteOrderDto;
import com.bbm.communitysystem.domain.vo.PageVo;
import com.bbm.communitysystem.domain.vo.UserAddrVo;
import com.bbm.communitysystem.domain.vo.WasteOrderVo;
import com.bbm.communitysystem.service.*;
import com.bbm.communitysystem.tools.DemoDate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bbm
 * @since 2025-02-28
 */
@Tag(name = "废品订单控制器")
@RestController
@RequestMapping("/waste-order")
@RequiredArgsConstructor
public class WasteOrderController {

    private final IWasteOrderService wasteOrderService;

    private final OSS oss;

    private final IUserAddrService iUserAddrService;

    private final IWastePriceService iWastePriceService;

    private final IOssFileService ossFileService;

    private final IStaffService staffService;

    private final IUserInfoService userInfoService;

    private final IWasteClassService iWasteClassService;



    @Operation(summary = "新增废品订单")
    @PostMapping
    public R<String> addWasteOrder(@RequestParam("img")MultipartFile img, @RequestParam("wasteId") Integer wasteId,
                                   @RequestParam("orderPrice") Double orderPrice, @RequestParam("updateBy") Integer updateBy,
                                   @RequestParam("userAddrId") Integer userAddrId) {

        WasteOrder wasteOrder = new WasteOrder();
        wasteOrder.setOrderPrice(orderPrice + 0.0);
        wasteOrder.setWasteId(wasteId);
        wasteOrder.setOrderStatus(0);
        wasteOrder.setAddr(userAddrId);
        wasteOrder.setOrderNum("T" + System.currentTimeMillis());


        Waste byId = iWastePriceService.getById(wasteId);

        wasteOrder.setOrderName(byId.getWasteName() + "订单" );

        if (!img.isEmpty()) {
            List<OssFile> ossFiles = oss.saveFile("waste-order", updateBy + "", img);
            OssFile ossFile = ossFiles.get(0);
            wasteOrder.setOssId(ossFile.getId());
        } else {
            wasteOrder.setOssId(null);
        }

        wasteOrder.setCreateBy(updateBy + "");
        wasteOrder.setCreateTime(System.currentTimeMillis() + "");
        wasteOrder.setUpdateBy(updateBy + "");
        wasteOrder.setUpdateTime(wasteOrder.getCreateTime());


        boolean save = wasteOrderService.save(wasteOrder);

        return save ? R.ok("新增成功") : R.error("新增失败");
    }


    @Operation(summary = "分页查询订单")
    @GetMapping
    public R<PageVo<WasteOrderVo>> getOrders(@RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer size,@RequestParam("userId") Integer id) {

        LambdaQueryWrapper<WasteOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WasteOrder::getCreateBy, id);
        lambdaQueryWrapper.orderByDesc(WasteOrder::getUpdateTime);
        Page<WasteOrder> page1 = wasteOrderService.page(new Page<>(page, size), lambdaQueryWrapper);



        PageVo<WasteOrderVo> pageVo = new PageVo<>(page1);

        pageVo.setRecords(page1.getRecords().stream()
                .map(this::getOrderVo).toList());


        return R.ok("获取成功", pageVo);
    }

    @Operation(summary = "获取订单详情")
    @GetMapping("/{id}")
    public R<WasteOrderVo> getOrderById(@PathVariable Integer id) {

        WasteOrder order = wasteOrderService.getById(id);

        return R.ok("获取成功", getOrderVo(order));
    }

    @Operation(summary = "更新订单信息")
    @PutMapping
    public R<String> updateOrder(@RequestBody WasteOrderDto dto) {
        boolean success = wasteOrderService.lambdaUpdate()
                .set(dto.getOrderName() != null && !dto.getOrderName().isEmpty(), WasteOrder::getOrderName, dto.getOrderName())
                .set(dto.getOrderPrice() != null && dto.getOrderPrice() != 0, WasteOrder::getOrderPrice, dto.getOrderPrice())
                .set(dto.getOrderStatus() != null, WasteOrder::getOrderStatus, dto.getOrderStatus())
                .set(dto.getStaffId() != null && dto.getStaffId() != 0, WasteOrder::getStaffId, dto.getStaffId())



                .set(WasteOrder::getUpdateTime, System.currentTimeMillis() + "")
                .set(WasteOrder::getUpdateBy, dto.getUpdateBy())
                .eq(WasteOrder::getId, dto.getId())
                .update();
        return success ? R.ok("更新成功") : R.error("更新失败");
    }

    @Operation(summary = "删除订单")
    @DeleteMapping("/{id}")
    public R<String> deleteOrder(@PathVariable Long id) {
        return wasteOrderService.removeById(id) ?
                R.ok("删除成功") : R.error("删除失败");
    }


    //推送订单给员工

    private WasteOrderVo getOrderVo(WasteOrder order) {
        WasteOrderVo wasteOrderVo = BeanUtil.copyProperties(order, WasteOrderVo.class);

        UserAddr byId = iUserAddrService.getById(order.getAddr());
        UserAddrVo userAddrVo = BeanUtil.copyProperties(byId, UserAddrVo.class);
        userAddrVo.setUserNick(userInfoService.getById(byId.getUserId()).getUserNick());
        wasteOrderVo.setUserAddrVo(userAddrVo);

        OssFile byId1 = ossFileService.getById(order.getOssId());

        if (byId1 != null) {
            wasteOrderVo.setClientUrl(byId1.getClientUrl());
        } else {
            wasteOrderVo.setClientUrl(null);
        }


        Waste waste = iWastePriceService.getById(order.getWasteId());
        wasteOrderVo.setWasteName(waste.getWasteName());


        WasteClass wasteClass = iWasteClassService.getById(waste.getWasteClassId());
        wasteOrderVo.setWasteClassName(wasteClass.getWasteClassName());
        wasteOrderVo.setStaff(staffService.getById(order.getStaffId()));


        wasteOrderVo.setCreateTime(DemoDate.getPostDate(order.getCreateTime()));
        wasteOrderVo.setUpdateTime(DemoDate.getPostDate(order.getUpdateTime()));

        return wasteOrderVo;
    }

}
